import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'

/**
 * HTTP请求配置接口
 */
export interface HttpConfig extends AxiosRequestConfig {
  // 可以扩展额外的配置选项
}

/**
 * SSE事件处理器接口
 */
export interface SSEHandler {
  onMessage?: (event: MessageEvent) => void
  onOpen?: (event: Event) => void
  onError?: (event: Event) => void
  onClose?: (event: Event) => void
}

/**
 * HTTP请求实例封装
 * 支持普通HTTP请求和SSE请求
 */
export class HttpClient {
  private instance: AxiosInstance
  private baseURL: string

  /**
   * 构造函数
   * @param baseURL 基础URL
   * @param config 请求配置
   */
  constructor(baseURL: string = '', config: HttpConfig = {}) {
    this.baseURL = baseURL
    this.instance = axios.create({
      baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
      ...config,
    })

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 可以在这里添加认证token等
        console.log(`🚀 发送请求: ${config.method?.toUpperCase()} ${config.url}`)
        return config
      },
      (error) => {
        console.error('❌ 请求拦截器错误:', error)
        return Promise.reject(error)
      },
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        console.log(`✅ 收到响应: ${response.status} ${response.config.url}`)
        return response
      },
      (error) => {
        console.error('❌ 响应拦截器错误:', error)
        return Promise.reject(error)
      },
    )
  }

  /**
   * 发送GET请求
   * @param url 请求URL
   * @param config 请求配置
   * @returns Promise响应数据
   */
  public async get<T = any>(url: string, config?: HttpConfig): Promise<T> {
    const response = await this.instance.get<T>(url, config)
    return response.data
  }

  /**
   * 发送POST请求
   * @param url 请求URL
   * @param data 请求数据
   * @param config 请求配置
   * @returns Promise响应数据
   */
  public async post<T = any>(url: string, data?: any, config?: HttpConfig): Promise<T> {
    const response = await this.instance.post<T>(url, data, config)
    return response.data
  }

  /**
   * 发送PUT请求
   * @param url 请求URL
   * @param data 请求数据
   * @param config 请求配置
   * @returns Promise响应数据
   */
  public async put<T = any>(url: string, data?: any, config?: HttpConfig): Promise<T> {
    const response = await this.instance.put<T>(url, data, config)
    return response.data
  }

  /**
   * 发送DELETE请求
   * @param url 请求URL
   * @param config 请求配置
   * @returns Promise响应数据
   */
  public async delete<T = any>(url: string, config?: HttpConfig): Promise<T> {
    const response = await this.instance.delete<T>(url, config)
    return response.data
  }

  /**
   * 发送PATCH请求
   * @param url 请求URL
   * @param data 请求数据
   * @param config 请求配置
   * @returns Promise响应数据
   */
  public async patch<T = any>(url: string, data?: any, config?: HttpConfig): Promise<T> {
    const response = await this.instance.patch<T>(url, data, config)
    return response.data
  }

  /**
   * 创建SSE连接
   * @param url SSE URL
   * @param handlers 事件处理器
   * @returns EventSource实例
   */
  public createSSE(url: string, handlers: SSEHandler = {}): EventSource {
    const fullUrl = this.baseURL ? `${this.baseURL}${url}` : url
    const eventSource = new EventSource(fullUrl)

    if (handlers.onMessage) {
      eventSource.onmessage = handlers.onMessage
    }

    if (handlers.onOpen) {
      eventSource.onopen = handlers.onOpen
    }

    if (handlers.onError) {
      eventSource.onerror = handlers.onError
    }

    // 注意：EventSource没有onclose事件，但我们可以监听error事件来处理连接关闭
    if (handlers.onClose) {
      eventSource.onerror = (event) => {
        // 检查是否是连接关闭的错误
        if (eventSource.readyState === EventSource.CLOSED) {
          handlers.onClose!(event)
        }
        // 同时调用原有的error处理器
        if (handlers.onError) {
          handlers.onError(event)
        }
      }
    }

    console.log(`🔗 创建SSE连接: ${fullUrl}`)
    return eventSource
  }

  /**
   * 获取原始的axios实例
   * @returns AxiosInstance
   */
  public getInstance(): AxiosInstance {
    return this.instance
  }

  /**
   * 设置认证token
   * @param token 认证token
   */
  public setAuthToken(token: string): void {
    this.instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
  }

  /**
   * 移除认证token
   */
  public removeAuthToken(): void {
    delete this.instance.defaults.headers.common['Authorization']
  }
}

// 默认导出实例（可以根据需要配置基础URL）
export const http = new HttpClient(import.meta.env.VITE_API_BASE_URL || '')

// 导出类型
export type { AxiosInstance, AxiosRequestConfig, AxiosResponse }
